package org.grow.leavejpa.service;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @Author: xwg
 * @CreateDate: 21-6-17
 */
@Service
public class NormalDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
//        System.out.println(object.getClass());
//        FilterInvocation fi = (FilterInvocation)object;
//        List<RoleInfo>
        Collection<? extends GrantedAuthority> rolesFromUser = authentication.getAuthorities();
        Collection<ConfigAttribute> rolesFromPermission  = configAttributes;
        System.out.println("decisionManager: 根据用户名查询到的角色信息："+rolesFromUser);
        System.out.println("decisionManager: 根据url查询到的角色信息："+rolesFromPermission);
        Boolean result = false;
        for (GrantedAuthority roleFromUser : rolesFromUser) {
            String authority = roleFromUser.getAuthority();
            for (ConfigAttribute roleFromPermission : rolesFromPermission) {
                String attribute = roleFromPermission.getAttribute();
                    if (authority.equals(attribute)){
                        result = true;
                        break;
                    }
            }
        }

        System.out.println("两个List<RoleInfo>有无交集? " +result);
        if (!result) throw new AccessDeniedException("资源被拦截");
        


    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
